package charlie.shop.web;

import charlie.shop.misc.Common;
import com.charlie.beans.Users;
import com.charlie.db.DAOLocal;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * View orders history servlet
 * 
 * @author Vitaliy Mostipaka <imprtat@gmail.com>
 */
@WebServlet(name = "OrderHistoryServlet", urlPatterns = {"/history"})
public class OrderHistoryServlet extends HttpServlet {

    final int itemsPerPage = 20;
    
    @EJB
    DAOLocal dao;

    /**
     * Return users order history
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        int page = Common.getPage(request);
        int from = (page - 1) * itemsPerPage + 1;
        int to = from + itemsPerPage;
        Users user = (Users) request.getSession(true).getAttribute("user");
        if (user != null) {
            request.setAttribute("list", dao.getOrdersByEmail(user.getEmail(), from, to));
        } else {
            response.sendRedirect(request.getContextPath());
            return;
        }
        int total = dao.getUserOrdersCount(user.getEmail());
        request.setAttribute("page", page);
        request.setAttribute("pagesCount", (int) Math.ceil((float)total / (float)20));
        request.getRequestDispatcher("/history.jsp").forward(request, response);
    }
}
